from io import BytesIO
from PIL import Image
from torchvision import transforms
from django.http import JsonResponse
from django.views.decorators.http import require_GET, require_POST
from growthAnalyzer.service import tool, forecastBodySize, video, predict, analysis

forecastBodySizeData_ = []


# 根据图片利用算法来预测体尺
@require_POST
def forecastBodySizeByImg(request):
    try:
        # 获取前端的图片
        # contentType = request.FILES.get("contentType")
        topViewCamera = request.FILES.get("topViewCamera")
        sideViewCamera = request.FILES.get("sideViewCamera")
        # colorImg = request.FILES.get("colorImg")
        depthCamera = request.FILES.get("depthCamera")

        hasNone, msg = tool.hasNone(topViewCamera, sideViewCamera, depthCamera)
        if hasNone:
            return JsonResponse({'code': 400, 'msg': msg, 'data': ''}, status=400)

        # 读取图像数据
        topViewCamera = topViewCamera.read()
        sideViewCamera = sideViewCamera.read()
        depthCamera = depthCamera.read()
        # 转换成PIL格式
        topViewCamera = Image.open(BytesIO(topViewCamera))
        sideViewCamera = Image.open(BytesIO(sideViewCamera))
        depthCamera = Image.open(BytesIO(depthCamera))
        # 将PIL图像转换为PyTorch Tensor
        transform = transforms.Compose([
            transforms.ToTensor(),
        ])
        topViewCamera = transform(topViewCamera)
        sideViewCamera = transform(sideViewCamera)
        depthCamera = transform(depthCamera)

        # try:
        #     # 从session中获取userId
        #     user_info = request.session.get("user_info")
        #     userId = user_info.get("userId")
        # except Exception as e:
        #     print(e)
        #     return JsonResponse({'code': 404, 'msg': '请先登录'}, status=404)

        # forecastBodySizeData = forecastBodySize.forecastBodySizeByImg(webcamImg=webcamImg, bgremovedIm=bgremovedImg,
        #                                                               colorImg=colorImg,
        #                                                               depthImg=depthImg, contentType=contentType,
        #                                                               userId=userId)

        forecastBodySizeData = predict.predict_images(topViewCamera, sideViewCamera, depthCamera)
        forecastBodySizeData_.append(forecastBodySizeData)
        return JsonResponse({'code': 200, 'msg': 'success',
                             'data': forecastBodySizeData}, status=200)
    except Exception as e:
        print(e)
        return JsonResponse({'code': 500, 'msg': '预测失败，服务器内部错误'}, status=500)


# 获取摄像头画面
# @require_GET
# def camera(request):
#     try:
#         cameras = video.detect_cameras()
#         return video.video_feed(cameras)
#     except Exception as e:
#         print(e)
#         return JsonResponse({'code': 500, 'msg': '显示失败，服务器内部错误'})


# 查看预测记录
@require_GET
def getPredictionRecords(request):
    try:
        try:
            # 从session中获取userId
            user_info = request.session.get("user_info")
            userId = user_info.get("userId")
        except Exception as e:
            print(e)
            return JsonResponse({'code': 404, 'msg': '请先登录'})

        forecastBodySizeLog = forecastBodySize.getPredictionRecords(userId)
        return JsonResponse({'code': 200, 'msg': '查询成功', 'data': forecastBodySizeLog})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 500, 'msg': '服务器内部错误'})


# # 育种分析
# @require_POST
# def breedingAnalysis(request):
#     try:
#         result = analysis.breedingAnalysis(forecastBodySizeData_)
#         return JsonResponse({'code': 200, 'msg': 'success', 'data': result})
#     except Exception as e:
#         print(e)
#         return JsonResponse({'code': 500, 'msg': '显示失败，服务器内部错误'})
#
#
# # 饲料配比
# @require_POST
# def feedRatio(request):
#     try:
#         result = analysis.feedRatio(forecastBodySizeData_)
#         return JsonResponse({'code': 200, 'msg': 'success', 'data': result})
#     except Exception as e:
#         print(e)
#         return JsonResponse({'code': 500, 'msg': '显示失败，服务器内部错误'})
